from rest_framework import serializers,exceptions
from apps.user.models import SysUser


class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    class Meta:
        model = SysUser
        fields = ('username', 'password')

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        user = SysUser.objects.filter(username=username).first()
        if not user:
           raise exceptions.AuthenticationFailed("认证失败,用户不存在")
        if not user.check_password(password):
            raise exceptions.AuthenticationFailed("认证失败，请检查账号密码")
        return {'user': user}


class SysUserSerializer(serializers.ModelSerializer):
    avatar_url = serializers.SerializerMethodField()  # 新增 avatar_url 字段

    class Meta:
        model = SysUser
        fields = ['id','username','avatar','avatar_url','email','phonenumber','login_date','remark']

    def get_avatar_url(self, obj):
        # 获取头像的 URL
        if obj.avatar:
            return obj.avatar.url
        return None